package com.zb.oauth.service.impl;

import com.zb.oauth.service.AuthService;
import com.zb.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    RestTemplate restTemplate;

    @Override
    public AuthToken login(String username, String password, String clientId, String secret) {
        List<ServiceInstance> instances = discoveryClient.getInstances("user-auth");
        ServiceInstance serviceInstance = instances.get(0);
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/oauth/token";
        System.out.println(url);
        //body中的参数
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("grant_type", "password");
        body.add("username", username);
        body.add("password", password);
        //header中的参数
        MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
        header.add("Authorization", httpHeadre(clientId, secret));
        //执行远程调用
        ResponseEntity<Map> responseEntity = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(body, header), Map.class);
        Map data = responseEntity.getBody();
        System.out.println("获取远程的登录结果......");
        System.out.println(data);
        AuthToken authToken = new AuthToken();
        authToken.setAccessToken(data.get("access_token").toString());
        authToken.setRefreshToken(data.get("refresh_token").toString());
        return authToken;
    }

    private static String httpHeadre(String clientId, String secret) {
        String str = clientId + ":" + secret;
        byte[] encode = Base64Utils.encode(str.getBytes());
        String strEncode = new String(encode);
        return "Basic " + strEncode;
    }

    public static void main(String[] args) {
        System.out.println(httpHeadre("xzzb", "xzzb"));
    }
}
